package com.foolishbird.sdk.ui.fragment;

import android.app.Activity;
import android.graphics.drawable.ColorDrawable;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.text.Editable;
import android.text.InputType;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.EditorInfo;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ListPopupWindow;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.TextView;

import androidx.annotation.Nullable;
import androidx.core.content.ContextCompat;
import androidx.fragment.app.Fragment;


import com.foolishbird.sdk.core.HttpEngineApi;
import com.foolishbird.sdk.core.HttpEngineConduits;
import com.foolishbird.sdk.params.bean.AccountInfo;
import com.foolishbird.sdk.ui.assist.OnItemRemoveListener;
import com.foolishbird.sdk.ui.assist.SpinnerListAdapter;
import com.foolishbird.sdk.ui.view.DialogFactory;
import com.foolishbird.sdk.ui.view.SwitchView;
import com.foolishbird.sdk.utils.ResUtils;
import com.foolishbird.sdk.utils.WL;

import java.util.ArrayList;
import java.util.List;

public class AccountLoginFragment extends Fragment implements View.OnClickListener, TextWatcher {

    private static final String TAG = AccountLoginFragment.class.getSimpleName();

    private Button mLoginSubmitBtn;
    private View mLoginUserAccountParentView;
    private EditText mLoginUserAccountEt;
    private EditText mLoginUserPasswordEt;
    private ImageButton mLoginSpinnerDropdownBtn;
    private SwitchView mSwitchView;
    private ListPopupWindow mPopupWindow;
    private Button mChangePasswordBtn, mOneKeyLoginBtn;

    private SpinnerListAdapter mPopupWindowAdatper;
    private List<AccountInfo> mAdapterData = new ArrayList<AccountInfo>();

    private FoolishBirdLoginFragment.OnUserActionListener getOnUserActionListener() {
        Activity activity = getActivity();
        if (activity instanceof FoolishBirdLoginFragment.OnUserActionListener) {
            return (FoolishBirdLoginFragment.OnUserActionListener) activity;
        }
        return null;
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, Bundle savedInstanceState) {
        super.onCreateView(inflater, container, savedInstanceState);
        int resource = ResUtils.getLayoutIdentifier(getActivity(), "hnssn_include_viewstub_login_account");
        View contentView = inflater.inflate(resource, null);

        mLoginUserAccountParentView = contentView.findViewById(ResUtils.getViewIdentifier(getActivity(), "activity_login_account_parent"));
        mLoginUserAccountEt = contentView.findViewById(ResUtils.getViewIdentifier(getActivity(), "activity_login_account_et"));
        mLoginUserPasswordEt = contentView.findViewById(ResUtils.getViewIdentifier(getActivity(), "activity_login_password_et"));
        mLoginUserPasswordEt.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD);
        mLoginSpinnerDropdownBtn = contentView.findViewById(ResUtils.getViewIdentifier(getActivity(), "activity_login_spinner_imgbtn"));
        mSwitchView = contentView.findViewById(ResUtils.getViewIdentifier(getActivity(), "activity_login_switch_btn"));
        mLoginSubmitBtn = contentView.findViewById(ResUtils.getViewIdentifier(getActivity(), "activity_login_submit_btn"));
        mChangePasswordBtn = contentView.findViewById(ResUtils.getViewIdentifier(getActivity(),"activity_login_forget_password_btn"));
        mOneKeyLoginBtn = contentView.findViewById(ResUtils.getViewIdentifier(getActivity(),"activity_login_register_btn"));

        mSwitchView.setOnClickListener(this);
        mLoginSpinnerDropdownBtn.setOnClickListener(this);
        mLoginSubmitBtn.setOnClickListener(this);
        mChangePasswordBtn.setOnClickListener(this);
        mOneKeyLoginBtn.setOnClickListener(this);

        mLoginUserAccountEt.addTextChangedListener(this);
        mLoginUserPasswordEt.addTextChangedListener(this);
        mLoginUserPasswordEt.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                if(actionId == EditorInfo.IME_ACTION_DONE&&mLoginSubmitBtn.isEnabled()){
                    submitUserLoginInfoByAccount();
                }
                Log.e("CodeEtOnKeyListener",actionId+".."+(event==null));
                return false;
            }
        });


        onInitData();

        return contentView;
    }

    private void onInitData() {
        HttpEngineConduits wanSDKDataDao = HttpEngineApi.getInstance().getEngineConduits();
        initAdapterData(wanSDKDataDao.readAllUserAccountInfo());
        if (!mAdapterData.isEmpty()) {
            mLoginSpinnerDropdownBtn.setEnabled(mAdapterData.size() > 1);
            mLoginUserAccountEt.setText(mAdapterData.get(0).getUsername());
            mLoginUserPasswordEt.setText(mAdapterData.get(0).getPassword());
            mLoginUserAccountEt.setSelection(mAdapterData.get(0).getUsername().length());
        } else {
            mLoginSpinnerDropdownBtn.setEnabled(false);
        }
    }

    private void initAdapterData(List<AccountInfo> accountInfo) {
        if (accountInfo != null && !accountInfo.isEmpty()) {
            mAdapterData.clear();
            mAdapterData.addAll(accountInfo);
        }
    }

    @Override
    public void onClick(View view) {
        if (view == mSwitchView) {
            switchUserLoginPasswordDisplayType();
        } else if (view == mLoginSpinnerDropdownBtn) {
            openSpinnerPopup(mLoginSpinnerDropdownBtn);
        } else if (view == mLoginSubmitBtn) {
            submitUserLoginInfoByAccount();
        }else if (view == mChangePasswordBtn) {
            nextToForgetPasswordActivity(getInputAccountUserName());
        } else if (view == mOneKeyLoginBtn) {
            nextToRegisterActivity();
        }
    }

    private void switchUserLoginPasswordDisplayType() {
        if (mSwitchView.isOpened()) {
            mLoginUserPasswordEt.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD);
        } else {
            mLoginUserPasswordEt.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD);
        }
    }

    private void openSpinnerPopup(View view) {
        if (view.isSelected()) {
            view.setSelected(false);
            destroyAndDismissSpinnerPopup();
        } else {
            view.setSelected(true);
            createAndShowSpinnerPopup();
        }
    }

    private void regenerateAdapteData(int position) {
        final int adapterSize = mAdapterData.size();
        position = position >= adapterSize ? adapterSize - 1 : position;
        if (position > 0) {
            AccountInfo accountInfo = mAdapterData.remove(position);
            mAdapterData.add(0, accountInfo);
        }
    }

    private void createAndShowSpinnerPopup() {
        int drawableId = ResUtils.getDrawableIdentifier(getActivity(), "wan_layerlist_login_dropdown_popup");
        Drawable drawable = ContextCompat.getDrawable(getActivity(), drawableId);
        mPopupWindowAdatper = new SpinnerListAdapter(mAdapterData.subList(1, mAdapterData.size()));
        mPopupWindow = new ListPopupWindow(getActivity());
        mPopupWindow.setBackgroundDrawable(drawable);
        mPopupWindow.setAdapter(mPopupWindowAdatper);
        mPopupWindow.setModal(true);
        mPopupWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                mLoginSpinnerDropdownBtn.setSelected(false);
            }
        });
        mPopupWindow.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Object item = parent.getItemAtPosition(position);
                if (item instanceof AccountInfo) {
                    mLoginUserAccountEt.setText(((AccountInfo) item).getUsername());
                    mLoginUserPasswordEt.setText(((AccountInfo) item).getPassword());
                    mLoginUserAccountEt.setSelection(((AccountInfo) item).getUsername().length());
                    destroyAndDismissSpinnerPopup();
                    regenerateAdapteData(position + 1);
                }
            }
        });

        mPopupWindowAdatper.setOnItemRemoveListener(new OnItemRemoveListener() {
            @Override
            public void OnItemRemove(View view, int position) {
                AccountInfo info = mPopupWindowAdatper.removeItem(position);
                HttpEngineApi.getInstance().getEngineConduits().deleteUserAccount(info);
                mAdapterData.remove(info);
                mLoginSpinnerDropdownBtn.setEnabled(mAdapterData.size() > 1);
                if (mAdapterData.size() > 1) {
                    mPopupWindowAdatper.notifyDataSetChanged();
                } else {
                    mPopupWindowAdatper.notifyDataSetChanged();
                    destroyAndDismissSpinnerPopup();
                }
            }
        });

        mPopupWindow.setAnchorView(mLoginUserAccountParentView);
        mPopupWindow.show();
        if (mPopupWindow.isShowing()) {
            ListView listview = mPopupWindow.getListView();
            listview.setDivider(new ColorDrawable(0x80ffffff));
            listview.setDividerHeight(1);
        }
    }

    private void destroyAndDismissSpinnerPopup() {
        if (mPopupWindow != null && mPopupWindow.isShowing()) {
            mPopupWindow.dismiss();
            mPopupWindow = null;
        }
    }

    private void checkSumbitButtonState() {
        String username = getInputAccountUserName();
        String password = getInputAccountPassword();
        if (TextUtils.isEmpty(username) || TextUtils.isEmpty(password)) {
            mLoginSubmitBtn.setEnabled(false);
        } else {
            mLoginSubmitBtn.setEnabled(true);
        }
    }

    public final String getInputAccountUserName() {
        return mLoginUserAccountEt.getText().toString().trim();
    }

    public final String getInputAccountPassword() {
        return mLoginUserPasswordEt.getText().toString().trim();
    }

    @Override
    public void beforeTextChanged(CharSequence s, int start, int count, int after) {

    }

    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {
        checkSumbitButtonState();
    }

    @Override
    public void afterTextChanged(Editable s) {

    }

    private void nextToForgetPasswordActivity(String loginAccount) {
        FoolishBirdLoginFragment.OnUserActionListener listener = getOnUserActionListener();
        if (listener != null) {
            listener.doNextToChangePassword(loginAccount);
        }

    }

    private void nextToRegisterActivity() {
        FoolishBirdLoginFragment.OnUserActionListener listener = getOnUserActionListener();
        if (listener != null) {
            listener.doNextToQuickRegister();
        }
    }

    private void submitUserLoginInfoByAccount() {
        String username = getInputAccountUserName();
        String password = getInputAccountPassword();

        WL.d(TAG, "submitUserLoginInfoByAccount  username: " + username + " password: " + password);

        if (TextUtils.isEmpty(username)) {
            DialogFactory.createConfirmDialog(getActivity(), getString(ResUtils.getStringIdentifier(getActivity(), "hnssn_hint_account"))).show();
            return;
        }

        if (TextUtils.isEmpty(password)) {
            DialogFactory.createConfirmDialog(getActivity(), getString(ResUtils.getStringIdentifier(getActivity(), "hnssn_hint_password"))).show();
            return;
        }

        if (password.contains(" ") || username.contains(" ")) {
            DialogFactory.createConfirmDialog(getActivity(), getString(ResUtils.getStringIdentifier(getActivity(), "hnssn_hint_password_blank"))).show();
            return;
        }

        FoolishBirdLoginFragment.OnUserActionListener listener = getOnUserActionListener();
        if (listener != null) {
            listener.doSubmitLoginInfo(username, password);
        }
    }
}
